/*
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-06-28 20:47:19
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2024-09-29 15:56:05
 * @FilePath: \code\src\views\home\components\Transfer.jsx
 * @Description: Vue to React conversion of transfer.vue
 */
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import PrintHtml from './demo'; // Assuming PrintHtml component exists

// Mock imports or replacements for Vue-specific imports
// Replace these with your actual React equivalents
const themeStore = {
  theme: {
    // theme properties
  },
  setCount: (email) => {
    // implementation
  }
};

// Inline styles
const styles = {
  container: {
    height: '100vh',
  }
};

const Transfer = () => {
  const navigate = useNavigate();
  const apiRef = useRef(null); // Reference for API calls (equivalent to proxy.$api)

  // State management
  const [state, setState] = useState({
    isLoadEnd: false,
    isPrintEnd: false,
    homeInfo: null,
    isShowBg: false,
    isShowArea: false,
    isShowLoadding: true,
    navIndex: 0,
    isSubmitting: false,
    isPrivileges: false,
    firstFunctionApply: false
  });
  
  const [message, setMessage] = useState("");
  
  // Constants
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  
  const ver = process.env.REACT_APP_VERSION; // Equivalent to VUE_APP_VERSION
  
  // SVG for loading spinner
  const svg = `
    <path class="path" d="
      M 30 15
      L 28 17
      M 25.61 25.61
      A 15 15, 0, 0, 1, 15 30
      A 15 15, 0, 1, 1, 27.99 7.5
      L 15 15
    " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
  `;

  // Handlers
  const listenPrintHtml = (e) => {
    setState(prevState => ({ ...prevState, isPrintEnd: e }));
  };
  
  const areaConfirm = (e) => {
    let homeInfo = JSON.parse(JSON.stringify(state.homeInfo));
    homeInfo.cityName = e.selectedOptions[e.selectedOptions.length - 1].text;
    localStorage.setItem("area", JSON.stringify(e));
    setState(prevState => ({ 
      ...prevState, 
      homeInfo: homeInfo,
      isShowArea: false 
    }));
    getHomeInfo(e.selectedOptions[e.selectedOptions.length - 1].text);
  };
  
  const getServerIP = async () => {
    try {
      const response = await fetch('https://api.ipify.org?format=json');
      const data = await response.json();
      return data.ip;
    } catch (error) {
      console.error('Error fetching server IP:', error);
      return null;
    }
  };
  
  const getHomeInfo = async (city) => {
    try {
      const ip = await getServerIP();
      const response = await fetch(`${process.env.REACT_APP_BASE_API_URL}/wechatApi/getHomeInfo?cityName=${city || ""}&ip=${ip}`);
      const res = await response.json();
      
      if (res.code === 200) {
        let area = localStorage.getItem("area")
          ? JSON.parse(localStorage.getItem("area"))
          : "";
        if (area) {
          res.data.cityName =
            area.selectedOptions[area.selectedOptions.length - 1].text;
        }
        localStorage.setItem("homeInfo", JSON.stringify(res.data));
        setState(prevState => ({ ...prevState, homeInfo: res.data }));
      }
    } catch (error) {
      console.error('Error fetching home info:', error);
    }
  };
  
  const bindClick = (e) => {
    if (!localStorage.getItem("userInfo")) {
      // Replace with your toast implementation
      alert("用户信息获取失败");
      return;
    }
    navigate('/home', { 
      state: { sendText: e } 
    });
  };
  
  const toHome = () => {
    if (!localStorage.getItem("userInfo")) {
      // Replace with your toast implementation
      alert("用户信息获取失败");
      return;
    }
    navigate('/home');
  };
  
  const isMobile = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
      userAgent
    );
  };
  
  const onSubmit = async () => {
    setState(prevState => ({ ...prevState, isSubmitting: true }));
    
    // Get and parse user info
    let userInfo = localStorage.getItem("userInfo");
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
    } else {
      console.error('未找到用户信息');
      setState(prevState => ({ ...prevState, isSubmitting: false }));
      return;
    }
    
    // Get user email
    const email = userInfo.user?.email;
    if (!email) {
      console.error('用户邮箱未找到');
      setState(prevState => ({ ...prevState, isSubmitting: false }));
      return;
    }
    
    try {
      // Build request body
      const requestBody = {
        email: email,
        reason: message,
        isDispose: true,
        applyTime: Date.now(),
      };
      
      const url = process.env.REACT_APP_BASE_API_URL + "/functionApply/insertFunctionApply";
      
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(requestBody)
      });
      
      const res = await response.json();
      
      if (res.code === 200) {
        setState(prevState => ({ 
          ...prevState, 
          isSubmitting: true,
          firstFunctionApply: false 
        }));
        
        // Show success dialog
        alert('申请成功!');
      } else {
        // Show error dialog
        alert(res.msg || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
    } finally {
      setState(prevState => ({ ...prevState, isSubmitting: false }));
    }
  };

  // Effects
  useEffect(() => {
    // Component mounted
    navigate('/home');
    
    // Cleanup function (equivalent to onUnmounted)
    return () => {
      // Cleanup code here
    };
  }, []);

  // CSS Styles
  const css = `
    /* Main wrapper */
    .wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
    }

    /* Loading styles */
    .loading {
      position: relative;
    }

    .loading::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(122, 122, 122, 0.8);
      z-index: 999;
    }

    .loading::after {
      content: attr(data-loading-text);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white;
      z-index: 1000;
    }

    /* Guide page styles */
    .yindaoye .transfer-header {
      position: absolute;
      top: 30px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      left: 0;
      z-index: 102;
    }

    .yindaoye .transfer-header .weather {
      font-size: 28px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 40px;
      color: #28334a;
      text-align: left;
      vertical-align: top;
      display: flex;
      justify-content: space-between;
      width: 100%;
    }

    .yindaoye .transfer-header .weather .area {
      display: flex;
      align-items: center;
    }

    .yindaoye .transfer-header .weather span {
      display: block;
      margin-bottom: 5px;
      margin-right: 20px;
    }

    .yindaoye .skip {
      padding: 12px 28px;
      height: 68px;
      border-radius: 40px;
      background: rgba(0, 45, 87, 0.2);
      font-size: 32px;
      font-weight: 500;
      letter-spacing: 0px;
      color: #ffffff;
    }

    .yindaoye .guide {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      background: url("../assets/images/guide_bg.gif") 0 1750px;
      background-size: cover;
    }

    .yindaoye .guide .video-background {
      width: 100%;
    }

    .yindaoye .guide img {
      width: 100%;
    }

    /* Robot section */
    .yindaoye .robot {
      position: absolute;
      left: 0;
      right: 0;
      top: 10%;
      margin: auto;
      text-align: center;
      z-index: 100;
    }

    .yindaoye .robot img {
      width: 20%;
      margin-top: -4%;
    }

    .yindaoye .robot .today-hot {
      font-size: 0;
      border-radius: 20px;
      background: rgba(255, 255, 255);
      box-shadow: 0px 0px 10px rgba(0, 125, 235, 0.3);
      padding: 34px 42px;
      width: 80%;
      margin: 0 auto;
    }

    .yindaoye .robot .today-hot .title {
      font-size: 32px;
      font-weight: 400;
      letter-spacing: 0px;
      color: #5393cf;
      text-align: left;
      font-weight: bold;
      float: left;
      clear: both;
      display: block;
      width: 100%;
      display: flex;
      align-items: center;
      gap: 18px;
    }

    .yindaoye .robot .today-hot .title .line {
      width: 1px;
      height: 30px;
      opacity: 1;
      background: rgba(83, 147, 207, 1);
    }

    .yindaoye .robot .today-hot .title .subtitle {
      font-size: 28px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 33.6px;
      color: rgba(83, 147, 207, 0.5);
      text-align: left;
      padding-top: 2px;
    }

    .yindaoye .robot .today-hot .title .privileges-span {
      font-size: 18px;
      text-align: center;
    }

    .yindaoye .robot .today-hot .list {
      font-size: 16px;
      width: 100%;
      clear: both;
    }

    .yindaoye .robot .today-hot .list .nav-tab {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
    }

    .yindaoye .robot .today-hot .list .nav-tab .nav-item {
      font-size: 24px;
      font-weight: 500;
      letter-spacing: 0px;
      line-height: 38px;
      color: rgba(83, 147, 207, 0.5);
      text-align: left;
      vertical-align: top;
      position: relative;
    }

    .yindaoye .robot .today-hot .list .nav-tab .nav-item .item-text {
      position: relative;
      z-index: 2;
    }

    .yindaoye .robot .today-hot .list .nav-tab .nav-item.active {
      color: #333;
    }

    .yindaoye .robot .today-hot .list .nav-tab .nav-item.active::after {
      content: "";
      display: block;
      position: absolute;
      background: linear-gradient(153.12deg, rgba(92, 178, 255, 1) 17.78%, rgba(255, 177, 177, 1) 100%);
      height: 8px;
      width: 100%;
      bottom: 2px;
      z-index: 1;
    }

    .yindaoye .robot .today-hot .list .scroll-box {
      overflow: scroll;
    }

    .yindaoye .robot .today-hot .list .scroll-box::-webkit-scrollbar {
      display: none;
    }

    .yindaoye .robot .today-hot .list .scroll-box .item {
      padding: 14px;
    }

    .yindaoye .robot .today-hot .list .scroll-box .item div {
      font-size: 20px;
    }

    .yindaoye .robot .today-hot .list .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      opacity: 1;
      border-radius: 12px;
      background: rgba(83, 147, 207, 0.1);
      margin-top: 12px;
      font-size: 24px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 40px;
      color: rgba(83, 147, 207, 1);
      text-align: left;
      vertical-align: top;
      padding: 14px;
    }

    .yindaoye .robot .today-hot .list .item > div {
      display: flex;
      align-items: center;
    }

    .yindaoye .robot .today-hot .list .item .point {
      width: 5px;
      height: 5px;
      opacity: 1;
      background: #5393cf;
      border-radius: 50%;
      margin-right: 16px;
    }

    .yindaoye .robot .opt-text {
      padding: 14px 0;
      border-radius: 44px;
      background: rgba(83, 147, 207, 1);
      box-shadow: 0px 4px 4px rgba(81, 136, 184, 0.5);
      font-size: 20px;
      font-weight: 700;
      letter-spacing: 0px;
      color: #ffffff;
      width: 200px;
      margin: 40px auto 0;
      opacity: 0;
    }

    .yindaoye .robot .end-opt-text {
      animation: upDown 500ms ease-in-out;
      opacity: 1;
    }

    /* Version display */
    .yindaoye .ver {
      position: absolute;
      bottom: 14px;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      z-index: 100;
      color: #4c4c4c;
      font-size: 20px;
      opacity: 0.5;
    }

    /* HTML text styles */
    .htmltext {
      margin: -55px 0 10px 0;
    }

    .htmltext > span {
      font-size: 26px;
      letter-spacing: 0px;
      color: #003a70;
    }

    .htmltext > p {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 26px;
      color: rgba(0, 58, 112, 1);
      margin-top: 9px;
    }

    .htmltext > p span {
      display: block;
      margin-top: 6px;
    }

    /* Form styles */
    .applySubmit {
      width: 80%;
      margin: 0 auto;
    }

    .applySubmit .elInput {
      padding: 20px 0 40px;
    }

    /* Animation */
    @keyframes upDown {
      0% {
        margin-top: 300px;
        opacity: 0;
      }
      100% {
        margin-top: 10%;
        opacity: 1;
      }
    }

    /* Area popup styles */
    .area-popup {
      border-radius: 8px 8px 0 0;
      box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
    }

    .area-popup h3 {
      padding: 16px;
      text-align: center;
      border-bottom: 1px solid #f0f0f0;
    }

    .area-popup .area-content {
      padding: 16px;
      max-height: calc(30vh - 120px);
      overflow-y: auto;
    }

    .area-popup .area-buttons {
      display: flex;
      padding: 12px 16px;
      border-top: 1px solid #f0f0f0;
    }

    .area-popup .area-buttons button {
      flex: 1;
      padding: 8px;
      margin: 0 8px;
      border-radius: 4px;
      border: none;
      background: #f0f0f0;
      cursor: pointer;
    }

    .area-popup .area-buttons button:last-child {
      background: #5393cf;
      color: white;
    }
  `;

  // UI Components (simplified mocks - replace with your UI library)
  const Icon = ({ name }) => <span className={`icon-${name}`}>{name}</span>;
  
  const Button = ({ children, type, round, disabled, onClick, className }) => (
    <button 
      className={`button ${type} ${round ? 'round' : ''} ${className || ''}`}
      disabled={disabled}
      onClick={onClick}
    >
      {children}
    </button>
  );
  
  const Input = ({ value, onChange, maxLength, placeholder, showWordLimit, className }) => (
    <div className={`input-container ${className || ''}`}>
      <input
        type="text"
        value={value}
        onChange={onChange}
        maxLength={maxLength}
        placeholder={placeholder}
      />
      {showWordLimit && (
        <div className="word-limit">{value.length}/{maxLength}</div>
      )}
    </div>
  );
  
  const Empty = ({ imageSize, description }) => (
    <div className="empty" style={{ fontSize: imageSize }}>
      <div className="empty-description">{description}</div>
    </div>
  );

  // Render
  return (
    <>
      <style>{css}</style>
      <div 
        style={styles.container}
        onClick={(e) => e.stopPropagation()}
        className={state.isShowLoadding ? 'loading' : ''}
        data-loading-text="Loading..."
        data-loading-spinner={svg}
        data-loading-svg-view-box="-10, -10, 50, 50"
        data-loading-background="rgba(122, 122, 122, 0.8)"
      >
        {!state.isShowLoadding && (
          <div className="wrapper">
            <div className="yindaoye">
              <div className="guide">
                {/* Background is handled via CSS */}
              </div>
              
              <div className="robot">
                <img src={require('@/assets/images/guide_rob.gif')} alt="" />
                <PrintHtml homeInfo={state.homeInfo} onListenPrintHtml={listenPrintHtml} />
                
                <div className="today-hot">
                  {state.isPrivileges ? (
                    <div>
                      {state.homeInfo?.dailyNews?.length > 0 && (
                        <div>
                          <div className="title">
                            <span>至一热搜</span> 
                            <span className="line"></span>
                            <span className="subtitle">最新内容早知道</span>
                          </div>
                          
                          <div className="list">
                            <div className="nav-tab">
                              {state.homeInfo?.dailyNews?.map((j, index) => (
                                <div 
                                  className={`nav-item ${state.navIndex === index ? 'active' : ''}`}
                                  key={index}
                                  onClick={() => setState(prevState => ({ ...prevState, navIndex: index }))}
                                >
                                  <div className="item-text">{j.typeName}</div>
                                </div>
                              ))}
                            </div>
                            
                            {state.homeInfo?.dailyNews[state.navIndex]?.list && 
                             state.homeInfo?.dailyNews[state.navIndex]?.list.length > 0 ? (
                              <div>
                                <div className="scroll-box">
                                  {state.homeInfo.dailyNews[state.navIndex].list.map((i, index) => (
                                    <div className="item" key={index} onClick={() => bindClick(i.quizContent)}>
                                      <div>
                                        <div className="point"></div>
                                        {i.quizContent}
                                      </div>
                                      <div>
                                        <img src={require('@/assets/images/arrow.png')} alt="" />
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            ) : (
                              <div>
                                <Empty imageSize="0" description="小助手正在努力学习中" />
                              </div>
                            )}
                          </div>
                          
                          <div 
                            className={`opt-text ${state.isPrintEnd ? 'end-opt-text' : ''}`}
                            onClick={toHome}
                          >
                            立即体验
                          </div>
                        </div>
                      )}
                    </div>
                  ) : (
                    <>
                      <div className="title">
                        <span className="privileges-span">
                          {state.firstFunctionApply 
                            ? '暂时没有权限哦！请点击下方按钮进行申请' 
                            : '您的申请正在审核中!'}
                        </span>
                      </div>
                      <div className="list"></div>
                      {state.firstFunctionApply && (
                        <div title="小助手功能申请" className="applySubmit">
                          <Input 
                            className="elInput"
                            value={message}
                            onChange={(e) => setMessage(e.target.value)}
                            maxLength={50}
                            placeholder="请输入申请原因"
                            showWordLimit
                          />
                          <Button 
                            className="elButton" 
                            type="primary" 
                            round
                            disabled={state.isSubmitting}
                            onClick={onSubmit}
                          >
                            提交
                          </Button>
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
              
              <div className="transfer-header">
                <div className="weather">
                  <div className="area">
                    <span 
                      className="area-name"
                      onClick={() => setState(prevState => ({ ...prevState, isShowArea: true }))}
                    >
                      <Icon name="location-o" />
                      {state.homeInfo?.cityName || ""}
                    </span>
                    
                    {state.homeInfo && (
                      <span>
                        <i className={`qi-${state.homeInfo?.currWeather?.icon}`}></i>
                        {state.homeInfo?.currWeather?.temp && (
                          <>&nbsp;{state.homeInfo.currWeather.temp}℃</>
                        )}
                        &nbsp;&nbsp;&nbsp;{state.homeInfo?.currWeather?.text}
                      </span>
                    )}
                  </div>
                  
                  <span>
                    {moment().format("MM-DD")} &nbsp;&nbsp;
                    {weekdays[moment().format("d")]}
                  </span>
                </div>
              </div>
              
              <div className="ver">{ver}</div>
            </div>
          </div>
        )}
        
        {/* Area selection popup - only shown when state.isShowArea is true */}
        {state.isShowArea && (
          <div 
            className="area-popup"
            style={{ 
              position: 'fixed', 
              bottom: 0, 
              left: 0, 
              width: '100%', 
              height: '30%',
              background: 'white',
              zIndex: 1000
            }}
          >
            <h3>地区选择</h3>
            <div className="area-content">
              {/* Area selection content would go here */}
            </div>
            <div className="area-buttons">
              <button onClick={() => setState(prevState => ({ ...prevState, isShowArea: false }))}>
                取消
              </button>
              <button onClick={areaConfirm}>确认</button>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default Transfer;